﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CompanyManageSystem.DLL
{
    public class BaseRepository<T> : IRepository<T>, IUnitOfWork where T : IEntity, new() //class
    {
        private  DbContext context;
        private  DbSet<T> dbset;

        public BaseRepository(DbContext dbContext)
        {
            this.context = dbContext;
            this.dbset = this.context.Set<T>();
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        public virtual void Add(T entity)
        {
            this.dbset.Add(entity);
        }

        public virtual void Update(T entity)
        {
            DbEntityEntry<T> entry = this.context.Entry<T>(entity);
            try
            {
                if (entry.State == EntityState.Detached)
                {
                    this.dbset.Attach(entity);
                    this.context.Entry<T>(entity);
                }
            }
            catch
            {
                object[] objArray1 = new object[] { entity.ID };
                T local = this.dbset.Find(objArray1);
                this.context.Entry<T>(local).GetDatabaseValues().SetValues(entity);
            }
        }



        /// <summary>
        /// 提交
        /// </summary>
        /// <returns></returns>
        public virtual int Commit()
        {
            return this.context.SaveChanges();
        }
    }
}
